/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
#include <cstddef>
#include<stdlib.h>
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x)
    {
        ListNode* lguard, * ltail, * gguard, * gtail, * cur = pHead, * ret;
        lguard = ltail = (ListNode*)malloc(sizeof(ListNode));
        gguard = gtail = (ListNode*)malloc(sizeof(ListNode));
        ltail->next = gtail->next = NULL;
        while (cur)
        {
            if (cur->val < x)
            {
                ltail->next = cur;
                ltail = ltail->next;
            }
            else
            {
                gtail->next = cur;
                gtail = gtail->next;
            }
            cur = cur->next;
        }
        ltail->next = gguard->next;
        gtail->next = NULL;
        ret = lguard->next;
        free(lguard);
        free(gguard);
        return ret;
    }
};